import logging
from functools import wraps

from flask import current_app as app
from sqlalchemy.exc import SQLAlchemyError

from ..globalvar import dbh


def transaction(session=None):
    def decorator(f):
        @wraps(f)
        def wrapper(*args, **kwargs):
            # Get db handler
            db = session
            if not db:
                db = dbh()
            # execute
            try:
                rv = f(*args, **kwargs)
                db.commit()
                return rv
            except SQLAlchemyError as e:
                db.rollback()
                app.logger.error('SQLAlchemyError: %r', e)
            return False
        return wrapper
    return decorator
